package com.learn.security.modules.sms.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.CommonResponse;
import com.learn.security.common.utils.RedisKeys;
import com.learn.security.common.utils.RedisOperator;
import com.learn.security.modules.sms.SmsUtil;
import com.learn.security.modules.sms.entity.SmsSendCode;
import com.learn.security.modules.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * 发送短信controller
 *
 * @author lee
 */
@Slf4j
@RequestMapping("/sms")
@RestController
public class SmsController {

    private static final String OK = "OK";

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 获取短信验证码
     *
     * @param mobile 电话
     * @return
     * @author Lee
     */
    @GetMapping("/code/{mobile}")
    public R code(@PathVariable String mobile) {
        log.info("获取验证码:{}", mobile);
        if (StrUtil.isBlank(mobile)) {
            return R.error("手机号不能为空");
        }
        Integer code = RandomUtil.randomInt(1000, 9999);
        SmsSendCode entity = new SmsSendCode();
        entity.setMobile(mobile);
        entity.setSmsCode(code);
        entity.setCreateTime(LocalDateTime.now());
        entity.insert();
        // 发送验证码
        CommonResponse resp = SmsUtil.sendSms(mobile, code.toString());
        log.info("发送短信结果:{}-{}", resp.getHttpStatus(), resp.getData());
        if (resp == null) {
            return R.error("获取验证码失败!");
        }
        JSONObject obj = JSONUtil.parseObj(resp.getData());
        entity.setMessage(obj.getStr("Message"));
        entity.setRequestId(obj.getStr("RequestId"));
        entity.setBizId(obj.getStr("BizId"));
        entity.setCode(obj.getStr("Code"));
        entity.updateById();
        // 发送成功
        if (OK.equalsIgnoreCase(entity.getCode())) {
            // 缓存验证码
            redisOperator.set(RedisKeys.REDIS_SMS_CODE + mobile, code + "", 300);
            return R.ok();
        }
        // 发送失败
        return R.error("获取验证码失败");
    }


}
